package com.mb.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

/**
 * oss存储
 *
 * @author
 * @create 2018-07-09 下午1:53
 **/

public class OSSUtil {

    // Endpoint以杭州为例，其它Region请按实际情况填写
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private static final String accessKeyId = "LTAISx7NUbstIW5a";
    private static final String accessKeySecret = "de4tc8tJ8frGJQaZr0ADGQNsufTcbn";

    private static OSSClient ossClient;

    static {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传文件
     * @param content
     * @return
     */
    public static String uploadImg(String key,byte[] content,String contentType){
        String filePath = "";
        String bucketName = "xmcr-img";

        //判断文件夹是否存在并创建
        checkAndCreateFolder(bucketName, key,true);

        if(ossClient == null){
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }

        ObjectMetadata objectMetadata = new ObjectMetadata();
        if(StringUtils.isBlank(contentType)){
            contentType = "image/png";
        }
        objectMetadata.setContentType(contentType);

        // 上传Byte数组
        ossClient.putObject(bucketName, key, new ByteArrayInputStream(content),objectMetadata);
        filePath = getUrl(bucketName,key);

        return filePath;
    }


    /**
     * 判断文件夹是否存在
     * @param bucketName
     * @param key
     * @return
     */
    public static void checkAndCreateFolder(String bucketName, String key,boolean isAutoCreate){
        // 判断文件是否存在
        int index = key.lastIndexOf("/");
        String keySuffixWithSlash = key.substring(0,index);
        boolean isExist = ossClient.doesObjectExist(bucketName, keySuffixWithSlash);
        if(!isExist && isAutoCreate){
            createFolder(bucketName,keySuffixWithSlash);
        }
    }


    /**
     * 创建文件夹
     * @param bucketName
     * @param keySuffixWithSlash
     */
    public static void createFolder(String bucketName, String keySuffixWithSlash){
        ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
    }


    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String bucketName, String key) {
        // 设置URL过期时间为20年  3600l* 1000*24*365*20
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }





}
